package com.gdou.teaching.controller.teacher;


import com.gdou.teaching.Enum.ResultEnum;
import com.gdou.teaching.dataobject.HostHolder;
import com.gdou.teaching.dto.CourseDTO;
import com.gdou.teaching.exception.TeachingException;
import com.gdou.teaching.form.CourseForm;
import com.gdou.teaching.form.CourseUpdateStuForm;
import com.gdou.teaching.service.*;
import com.gdou.teaching.util.ResultVOUtil;
import com.gdou.teaching.vo.ClazzVO;
import com.gdou.teaching.vo.CourseVO;
import com.gdou.teaching.vo.ResultVO;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ProjectName: teaching
 * @Package: com.gdou.teaching.controller
 * @ClassName: TeacherCourseController
 * @Author: carrymaniac
 * @Description: 教师端课程controller
 * @Date: 2019/9/20 6:19 下午
 * @Version:
 */
@Slf4j
@Controller
@RequestMapping("/teacher/course")
public class TeacherCourseController {
    @Autowired
    private CourseService courseService;
    @Autowired
    private UserService userService;
    @Autowired
    private ExperimentService experimentService;
    @Autowired
    private ClazzService clazzService;
    @Autowired
    private AchievementService achievementService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private RecordService recordService;

    /**
     * 更新所需信息。updatepage
     *
     * @param courseId
     * @return
     */
    @GetMapping("/index")
    public ResultVO index(@RequestParam(value = "courseId") Integer courseId) {
        CourseVO courseVO = new CourseVO();
        List<Map.Entry<Integer, String>> clazzList = clazzService.getAllClazzList();
        HashMap<String, Object> map = new HashMap<>();
        //如果传入courseId不为空,为更新操作
        ;
        if (!StringUtils.isEmpty(courseId)) {
            CourseDTO courseDTO = courseService.detail(courseId);
            courseDTO.setClazzList(achievementService.getClazzIdListByCourseId(courseId));
            BeanUtils.copyProperties(courseDTO, courseVO);
            List<ClazzVO> clazzListforCourse = courseDTO.getClazzList();
            List<Integer> clazzIdListforCourse = clazzListforCourse.stream().map(c -> c.getClassId()).collect(Collectors.toList());
            clazzList =
                    clazzList.stream().filter(entry -> !clazzIdListforCourse.contains(entry.getKey()))
                            .collect(Collectors.toList());
            map.put("course", courseVO);
        }
        map.put("classForSelect", clazzList);
        return ResultVOUtil.success(map);
    }

    /**
     * 更新或新增课程
     *
     * @param form
     * @param bindingResult
     * @return
     */
    @PostMapping("/save")
    public ResultVO save(@Valid CourseForm form,
                         BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("参数不正确：{}" + form);
            throw new TeachingException(ResultEnum.PARAM_ERROR.getCode(), ResultEnum.PARAM_ERROR.getMsg());
        }
        CourseDTO courseDTO = new CourseDTO();
        BeanUtils.copyProperties(form, courseDTO);
        try {
            courseService.save(courseDTO);
        } catch (TeachingException e) {
            log.error("保存课程,发生异常:{}", e);
            return ResultVOUtil.fail(ResultEnum.COURSE_SAVE_ERROR.getCode(), e.getMessage());
        }

        List<Integer> clazzIdList = form.getAddClazzIdList();
        List<String> studentIdList = form.getAddStudentIdList();


        //todo  异步新增成绩表 addAchievementByClazzId
        return ResultVOUtil.success();
    }

    @PostMapping("/update")
    //课程详情
    @ApiOperation(value = "更新课程的上课人数", notes = "根据课程Id(courseId),学号(userNumber)更新")
    @ApiImplicitParams({@ApiImplicitParam(name = "form", value = "提交表单", required = true, dataType = "CourseUpdateStuForm", paramType = "")})
    public ResultVO update(@Valid CourseUpdateStuForm form,
                           BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("参数不正确：{}" + form);
            throw new TeachingException(ResultEnum.PARAM_ERROR.getCode(), ResultEnum.PARAM_ERROR.getMsg());
        }
        try {
            //修改
            achievementService.addAchievementByStudentList(form.getCourseId(), form.getAddStudentIdList());
            achievementService.deleteAchievementByStudentList(form.getCourseId(), form.getDeleteStudentIdList());
        } catch (TeachingException e) {
            log.error("保存课程,发生异常:{}", e);
            return ResultVOUtil.fail(ResultEnum.PARAM_ERROR.getCode(), e.getMessage());
        }
        return ResultVOUtil.success();
    }


    @GetMapping("/invalid")
    public ResultVO invalid(@RequestParam("courseId") Integer courseId) {
        try {
            courseService.invalid(courseId);
        } catch (TeachingException e) {
            log.error("注销课程,发生异常");
            return ResultVOUtil.fail(ResultEnum.COURSE_INVALID_ERROR.getCode(), e.getMessage());
        }
        return ResultVOUtil.success();
    }

    @GetMapping("/restore")
    public ResultVO restore(@RequestParam("courseId") Integer courseId) {
        try {
            courseService.restore(courseId);
        } catch (TeachingException e) {
            log.error("恢复课程,发生异常");
            return ResultVOUtil.fail(ResultEnum.COURSE_INVALID_ERROR.getCode(), e.getMessage());
        }
        return ResultVOUtil.success();
    }
}
